package com.wwdx.controller.admin;

import com.google.common.collect.Maps;
import com.wwdx.controller.base.BaseController;
import com.wwdx.model.WwdxBookChapterModel;
import com.wwdx.utils.ConstantHolder;
import freemarker.template.*;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.Date;
import java.util.Locale;
import java.util.Map;

/**
 * @author liguoliang
 * @date 2017/09/23
 */
@Controller
@RequestMapping("/system/wwdx_bookchapter")
public class WwdxBookChapterController extends BaseController{

    /**
     * 新增
     */
    @RequestMapping("/create")
    public ModelAndView create(Long bookid) {
        ModelAndView mav = new ModelAndView("/system/wwdx_book/chapter_create");
        mav.addObject("bookid", bookid);
        return mav;
    }

    /**
     * 保存新增
     */
    @RequestMapping("/save")
    public String save(WwdxBookChapterModel model, HttpServletRequest request, RedirectAttributes attributes) {
        this.execute(request,model);
        model.setChapterid(System.currentTimeMillis() / 1000);
        model.setGmt_created(new Date());
        model.setGmt_modified(new Date());
        wwdxBookChapterService.save(model);
        this.execute2(model,request);
        attributes.addAttribute("bookid",model.getBookid());
        return "redirect:/system/wwdx_book/chapter_list";
    }

    /**
     * 修改
     */
    @RequestMapping("/edit")
    public ModelAndView edit(Long id) {
        ModelAndView mav = new ModelAndView("/system/wwdx_book/chapter_edit");
        WwdxBookChapterModel wwdxBookChapterModel = wwdxBookChapterService.getById(id);
        mav.addObject("model", wwdxBookChapterModel);
        mav.addObject("bookid", wwdxBookChapterModel.getBookid());
        return mav;
    }

    /**
     * 图片上传
     */
    private void execute(HttpServletRequest request, WwdxBookChapterModel model){
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        String fileUrl = "fileUrl";
        fileMap.forEach((k,file)->{
            if (file.getSize() > 0) {
                if (fileUrl.equalsIgnoreCase(file.getName())) {
                    model.setChaptervideo(super.upload(file, directory + ConstantHolder.Constant.COVER));
                }
            }
        });
    }

    /**
     * 生成文稿
     */
    private void execute2(WwdxBookChapterModel model, HttpServletRequest request){
        Long bookid = model.getBookid();
        String key = String.format(ConstantHolder.BOOK_CHAPTER_LIST, bookid);
        redisTemplate.delete(key);
        taskExecutor.execute(()-> {
            Map<String, Object> map = Maps.newHashMapWithExpectedSize(2);
            map.put("title",model.getChaptername());
            map.put("content",model.getContent());
            //生成文件地址
            String savepath = directory + ConstantHolder.Constant.BOOKCHAPTER + model.getChapterid() + ".html";
            new FreeMarkerTemplate(request).geneHtmlFile(map,savepath, ConstantHolder.Constant.HTMLFILE_FTL);
        });
    }

    private class FreeMarkerTemplate {

        private Logger logger = LoggerFactory.getLogger(this.getClass());

        private Configuration configuration;

        /**
         * 获取freemarker的配置. freemarker本身支持classpath,目录和从ServletContext获取.
         */
        FreeMarkerTemplate(HttpServletRequest req) {
            File templateFile = new File(req.getSession().getServletContext().getRealPath("/WEB-INF/ftl/"));
            Version version = new Version("2.3.23", true, new Date());
            configuration = new Configuration(version);
            configuration.setObjectWrapper(new DefaultObjectWrapper(version));
            configuration.setEncoding(Locale.CHINA, ConstantHolder.Constant.UTF8);
            try {
                configuration.setDirectoryForTemplateLoading(templateFile);
            } catch (IOException e) {
                logger.error("错误信息：{}",e.getMessage());
            }
        }

        /**
         * 生成静态文件
         */
        private void geneHtmlFile(Map<String, Object> map,String savepath, String htmlFileFtl) {
            try (Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(savepath)), ConstantHolder.Constant.UTF8))){
                Template template = this.configuration.getTemplate(htmlFileFtl);
                template.process(map, out);
            } catch (TemplateException | IOException e) {
                logger.error("错误信息：{}",e.getMessage());
            }
        }
    }
    
    /**
     * 保存修改
     */
    @RequestMapping("/update")
    public Object update(HttpServletRequest request, WwdxBookChapterModel model, RedirectAttributes attributes) {
        this.execute(request,model);
        model.setGmt_modified(new Date());
        wwdxBookChapterService.update(model);
        this.execute2(model,request);
        attributes.addAttribute("bookid",model.getBookid());
        return "redirect:/system/wwdx_book/chapter_list";
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    @RequiresRoles("super")
    public String delete(Long id, RedirectAttributes attributes) {
        WwdxBookChapterModel wwdxBookChapterModel = wwdxBookChapterService.getById(id);
        wwdxBookChapterService.delete(wwdxBookChapterModel);
        Long bookid = wwdxBookChapterModel.getBookid();
        String key = String.format(ConstantHolder.BOOK_CHAPTER_LIST, bookid);
        redisTemplate.delete(key);
        attributes.addAttribute("bookid",bookid);
        return "redirect:/system/wwdx_book/chapter_list";
    }
}